/*
 * @Description:
 * @Author: zheng yiliang
 * @Date: 2021-03-28 18:16:43
 * @LastEditTime: 2021-04-18 20:23:31
 * @LastEditors: zheng yiliang
 */

const jwt = require('jsonwebtoken')
// const JWT_TOKEN_NAME = "TokenKey"
// const JWT_EXPIRATION = 60 * 60 * 24
const JWT_EXPIRATION = 60 * 60 * 24
const JWT_SECRET = '#zyl1315MC#'
const { ErrorModel } = require('../util')

// 生成签名
const sign = data => {
  try {
    return jwt.sign(data, JWT_SECRET, { expiresIn: JWT_EXPIRATION })
  } catch (error) {
    throw new Error('加密失败')
  }
}

// 设置 token
exports.setToken = (data) => {
  // console.log('设置token', data)
  return sign(data)
}


// 校验 token
const verify = (data, secret = JWT_SECRET) => {
  try {
    return jwt.verify(data, secret)
  } catch (error) {
    throw new Error('用户信息校验不通过')
  }
}

// 获取token
exports.getToken = (req) => {
  let data = {}
  if (req.get('X-Token')) {
    try {
      data = verify(req.get('X-Token'))
      return data._id
    } catch (error) {
      return error
    }
  }
}

// 清除 cookie
// exports.cleanToken = res => {
//   // res.cleanCookie(JWT_TOKEN_NAME)
// }